package com.heng.threadLocalDemo;

import org.junit.Test;

import java.lang.ref.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

class MyObject{
    protected void finalize() throws Throwable{
        System.out.println("---invoke finalize method");
    }
}


public class ReferenceDemo3 {
    public static void main(String[] args) {
        MyObject myObject = new MyObject();
        ReferenceQueue<MyObject> referenceQueue = new ReferenceQueue<>();
        PhantomReference<MyObject> phantomReference = new PhantomReference<>(myObject,referenceQueue);

        System.out.println(phantomReference.get());
        Reference<? extends MyObject> re = referenceQueue.poll();
        System.out.println(re);
    }

    @Test
    public void weakReference() {
        WeakReference<MyObject> weakReference = new WeakReference<>(new MyObject());
        System.out.println("---gc before 内存够用： "+weakReference.get());
        System.gc();
        try {TimeUnit.SECONDS.sleep(1);}catch (InterruptedException e) {e.printStackTrace();}
        System.out.println("---gc after 内存够用： "+weakReference.get());
    }

    @Test
    public void softReference() {
        //内存够用，软引用不会被回收！
        //内存不够用，软引用会被回收！
        SoftReference<MyObject> softReference = new SoftReference<>(new MyObject());

        System.out.println("---softReference： "+softReference.get());
        System.gc();
        try {TimeUnit.SECONDS.sleep(1);}catch (InterruptedException e) {e.printStackTrace();}

        System.out.println("---gc after: " + softReference.get());
    }


    @Test
    public void strongReference() {
        MyObject myObject = new MyObject();
        System.out.println("gc before:" + myObject);

        myObject = null;
        System.gc();//人工开启GC，一般不用
        System.out.println("gc after:" + myObject);
    }
}
